<template>
  <view class="page-container-wrap">
    <view class="page-container">
      <view class="page-header">
        <u-navbar :autoBack="true" :fixed="false" @leftClick="handleBack">
          <view class="u-nav-slot" slot="center">
            <view class="username">{{ nick }}</view>
          </view>
        </u-navbar>
        <!-- 客服服务 -->
        <view class="actions m-20" v-if="serveId">
          <view class="action-item" @click="handleSendServiceMessage">
            <!-- <view class="iconfont icon-xiaotubiao-01"></view> -->
            <view class="action-item__text">发送服务</view>
          </view>
        </view>
        <!--非客服操作-->
        <template v-if="position">
          <view class="actions" v-if="['02', '03'].includes(userInfo.userType)">
            <view class="action-item" v-if="isCompany" @click="resumeModal = true">
              <view class="iconfont icon-icon-"></view>
              <view class="action-item__text">求简历</view>
            </view>
            <view class="action-item" v-if="!isCompany" @click="handleOpenResumePopup">
              <view class="iconfont icon-icon-"></view>
              <view class="action-item__text">发简历</view>
            </view>
            <view class="action-item" @click="handleChangeMobile">
              <view class="iconfont icon-xiaotubiao-01"></view>
              <view class="action-item__text">换电话</view>
            </view>
            <view class="action-item" @click="handleChangeWX">
              <view class="iconfont icon-xiaotubiao-02"></view>
              <view class="action-item__text">换微信</view>
            </view>
            <view v-if="jobDetail" class="action-item" @click="handleSendJobMessage">
              <view class="iconfont icon-a-gangweiguanli1"></view>
              <view class="action-item__text">发送岗位</view>
            </view>
            <view v-if="!jobDetail" class="action-item" @click="refusePopup = true">
              <view class="iconfont icon-guanbi"></view>
              <view class="action-item__text">{{ isCompany ? '不合适' : '不感兴趣' }}</view>
            </view>
          </view>
        </template>
      </view>
      <view class="page-body">
        <MessageList :messages="messageList" />
      </view>
      <view class="page-footer">
        <view class="message-input">
          <u-input placeholder="请输入消息内容" v-model.trim="content" />
        </view>
        <view class="send-button">
          <u-button type="primary" text="发送" :disabled="!content" @click="handleSendTextMessage" />
        </view>
        <u-icon name="plus-circle" color="#666D80" size="30" @click="handleChoose" />
      </view>
      <view class="choose-file-image" v-if="visible">
        <view class="choose-item" @click="handleSendImage">
          <div class="iconfont icon-a-xiangcezhaopian-m fontS40"></div>
          <div>相册</div>
        </view>
        <view class="choose-item" @click="handleSendImage('camera')">
          <div class="iconfont icon-paizhao fontS40"></div>
          <div>拍照</div>
        </view>
        <view class="choose-item" @click="handleSendFile">
          <div class="iconfont icon-wenjian fontS40"></div>
          <div>文件</div>
        </view>
      </view>
    </view>
    <u-modal :show="resumeModal" title="确定向牛人请求简历吗？" content='确定后，简历请求将发送至对方，对方同意后' :showCancelButton="true"
      confirmColor="#37AF71" @cancel="resumeModal = false" @confirm="handleRequestResume"></u-modal>
    <u-modal :show="mobileModal" title="确定与对方交换电话吗？" :showCancelButton="true" confirmColor="#37AF71"
      @cancel="mobileModal = false" @confirm="handleSendMobileMessage">
      <view class="modal-content-slot">
        交换成功后，双方可以查看彼此的电话号，您当前电话号：
        <view class="green-text">{{ mobileDesensitize(mobile) }}</view>
      </view>
    </u-modal>
    <u-modal :show="wxModal" title="确定与对方交换微信吗？" :showCancelButton="true" confirmColor="#37AF71"
      @cancel="wxModal = false" @confirm="handleSendWXMessage">
      <view class="modal-content-slot">
        交换成功后，双方可以查看彼此的微信，您当前微信：
        <view class="green-text">{{ wxDesensitize(userInfo.wx) }}</view>
      </view>
    </u-modal>
    <RefusePopup :show="refusePopup" :is-company="isCompany" @close="refusePopup = false"
      @confirm="handleConfirmRefuse" />
    <ResumePopup :show="resumePopup" :resumeList="resumeList" @close="resumePopup = false"
      @confirm="handleConfirmResume" />
  </view>
</template>
<script>
import { getEResumeList } from '../../api/user';
import { findServePersonalDetailApp, findServeDetailApp } from '../../api/serve';
import { formatMessageList } from './utils/message';
import { getFilePath, mobileDesensitize, showToast, wxDesensitize } from "./utils/common";
import { uploadImage, uploadFile } from './utils/upload';
import RefusePopup from "./components/RefusePopup.vue";
import ResumePopup from "./components/ResumePopup.vue";
import MessageList from './MessageList/index.vue';
import { getPositionDetail } from "../../api";

export default {
  components: {
    RefusePopup,
    ResumePopup,
    MessageList,
  },
  data() {
    return {
      type: null,
      jobId: null, // 岗位id
      jobDetail: null,
      serveId: null, // 服务id
      serviceDetail: null, // 服务详情
      visible: false,
      nick: '', // 昵称
      toUserId: '', // `customer_${305}`,
      content: '',
      messageList: [],
      resumeModal: false,
      mobileModal: false,
      wxModal: false,
      refusePopup: false,
      resumePopup: false,
      resumeList: [],
      position: null
    }
  },
  computed: {
    isReady() {
      return this.$store.state.tim.isReady
    },
    userInfo() {
      return this.$store.state.user.userInfo
    },
    mobile() {
      return this.userInfo.phonenumber || this.userInfo.linkphone
    },
    isCompany() {
      return this.$store.state.user.userInfo.userType === '03';
    },
  },
  watch: {
    jobId: {
      handler(value) {
        if (value) {
          this.fetchJobDetail(value);
        } else {
          this.jobDetail = null;
        }
      },
      immediate: true,
      deep: true
    }
  },
  onLoad(options) {
    // 如果是用户进来就获取在线简历
    if (this.$store.state.user.userInfo.userType === '02') {
      this.fetchResumeAttachments();
    }
    this.jobId = options.jobId;
    this.serveId = options?.serveId;
    this.type = options?.type;
    this.toUserId = options?.toUserId;
    this.position = options?.position
    console.log('toUserId ===>', this.toUserId);
    this.nick = options?.nick;
    this.fetchHistoryMessages();
    if (this.serveId) {
      this.getServiceDetail();
    }
  },
  methods: {
    mobileDesensitize,
    wxDesensitize,
    handleBack() {
      uni.navigateBack()
    },
    // 获取电子简历
    fetchResumeAttachments() {
      getEResumeList().then((res) => {
        if (res.code === 200) {
          this.resumeList = (res.rows || []).map((item) => {
            return {
              size: (item.fileSize / 1024).toFixed(2),
              name: item.fileName,
              fileExtension: item.fileExtension,
              url: getFilePath(item.fileUrl),
              updateTime: item.updateTime,
            }
          })
        }
      }).catch((error) => {
        showToast(error.msg)
        this.resumeList = []
      })
    },
    sendMessage(data, type) {
      this.$chat.sendMessage({
        toUserID: this.toUserId,
        data,
      }).then((res) => {
        console.log('sendMessage ===>', res)
        if (res.code === 0 && res.data?.message) {
          const newMessages = formatMessageList([res.data.message])
          this.messageList = this.messageList.concat(newMessages)
        }
        if (type === 'text') {
          this.content = ''
        }
      }).catch((error) => {
        console.log('error ---->', error)
        showToast(error.message)
      })
    },
    // 发送文本消息
    sendTextMessage(content, type) {
      this.sendMessage({
        type: 'text',
        value: {
          text: content,
        }
      }, type)
    },
    // 发送岗位消息
    handleSendJobMessage() {
      if (!this.jobDetail) {
        uni.showToast({ icon: 'none', title: '没有岗位信息' });
        return;
      }
      const val = this.jobDetail;
      this.sendMessage({
        type: 'work',
        value: {
          id: val.id, // 服务id
          name: val.professionName, // 岗位名称
          company: val.companyName, // 公司名称
          city: val.areaName, // 工作城市
          salary: val.salary, // 薪资范围
          keywords: val.postKey, // 岗位关键字
          // 新增，11.20
          companySize: val.companySizeName // 公司规模，直接文字描述，不使用数字表示
        },
      });
    },
    // 发送服务消息
    handleSendServiceMessage() {
      const {
        carouselImageUrls,
        serveName,
        priceType,
        chargePerPerson,
        servePeriodUnit,
        attributeDtos = [],
      } = this.serviceDetail || {};
      const attribute = attributeDtos ? attributeDtos[0] : '';
      const data = {
        id: this.serveId, // 服务id
        cover: carouselImageUrls.split(',')[0], // 服务封面图
        name: serveName, // 服务名称
        price: attribute?.price, // 服务价格
        actPrice: attribute?.presentPrice, // 服务现价
        serviceType: 'cmp',
        priceType: priceType, // 服务类型  新增，
        chargePerPerson: chargePerPerson || '', // 新增，周期性服务使用，直接详情带过来
        servePeriodUnit: servePeriodUnit || '' // 新增，周期性服务使用，直接详情带过来
      }
      this.sendMessage({ type: 'service', value: data });
    },
    handleOpenResumePopup() {
      if (!this.resumeList.length) {
        showToast('暂无附件简历，请先取添加附件简历')
        return
      }
      this.resumePopup = true
    },
    // 发送简历消息
    handleConfirmResume(resume) {
      this.resumePopup = false
      this.sendMessage({
        type: 'file',
        value: {
          name: resume.name,
          size: resume.size,
          url: resume.url
        }
      })
    },
    // 发送图片
    handleSendImage(sourceType) {
      uploadImage((file) => {
        this.sendMessage({ type: 'image', value: file })
      }, sourceType);
    },
    handleSendFile() {
      uploadFile((file) => {
        this.sendMessage({ type: 'file', value: file })
      })
    },
    // 选择文件
    handleChoose() {
      this.visible = !this.visible;
      // if (this.serveId) {

      // } else {
      //   this.handleSendImage();
      // }
    },
    // 求简历
    handleRequestResume() {
      this.sendTextMessage('我想要一份您的简历', 'resume')
      this.resumeModal = false
    },
    // 不感兴趣/不合适
    handleConfirmRefuse(currentReason) {
      this.sendTextMessage(currentReason, 'refuse')
      this.refusePopup = false
    },
    // 交换电话
    handleChangeMobile() {
      if (!this.mobile) {
        showToast('您未设置电话号码');
        return
      }
      this.mobileModal = true;
    },
    // 发送电话消息
    handleSendMobileMessage() {
      this.sendTextMessage(`我的手机号：${this.mobile}`, 'mobile')
      this.mobileModal = false;
    },
    // 交换微信
    handleChangeWX() {
      if (!this.userInfo.wx) {
        showToast('您未设置微信');
        return
      }
      this.wxModal = true;
    },
    // 发送微信消息
    handleSendWXMessage() {
      this.sendTextMessage(`我的微信：${this.userInfo.wx}`, 'weixin')
      this.wxModal = false;
    },
    // 发送文本消息
    handleSendTextMessage() {
      this.sendTextMessage(this.content, 'text')
    },
    // 获取消息列表
    fetchHistoryMessages() {
      setTimeout(() => {
        this.$chat.$timInstance.getMessageList({
          conversationID: `C2C${this.toUserId}`,
        }).then((res) => {
          this.messageList = formatMessageList(res.data.messageList)
          console.log('this.messageList---->', this.messageList)
          if (!this.jobId) {
            const lastWorkMessage = this.messageList.findLast((item) => item.m_type === 'WorkMessage')
            if (lastWorkMessage) {
              const data = lastWorkMessage.m_data;
              console.log('workDetail ===>', data);
              this.jobDetail = {
                id: data.id,
                professionName: data.name,
                companyName: data.company,
                areaName: data.city,
                salary: data.salary,
                postKey: data.keywords,
                companySizeName: data.companySize,
              };
            }
          }
        })
      }, 1000);
    },
    // 获取服务详情
    getServiceDetail() {
      const request = this.userInfo.userType === '03' ? findServeDetailApp : findServePersonalDetailApp;
      request(this.serveId).then((res) => {
        this.serviceDetail = res?.data;
      });
    },
    // 获取岗位详情
    fetchJobDetail(jobId) {
      getPositionDetail(jobId).then(res => {
        this.jobDetail = res.data;
      })
    },
    // TODO 待删除调试代码
    handleDeleteMessage() {
      const length = this.messageList.length
      this.$chat.$timInstance.deleteMessage(this.messageList.slice(length - 1, length)).then((res) => {
        console.log('删除消息成功 ===>', res)
        this.messageList.pop()
      })
    },
    // TODO 待删除调试代码
    handleClearMessage() {
      this.$chat.$timInstance.clearHistoryMessage(this.conversation.conversationID).then((res) => {
        console.log('清空消息成功 ===>', res)
        this.messageList = []
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.page-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f7f7f7;

  .page-header {
    .actions {
      display: flex;
      align-items: center;
      padding: 15px 0 13px;
      background: #fff;

      .action-item {
        flex: 1;
        text-align: center;

        .iconfont {
          margin: 0 auto 5px;
          color: #333;
          font-size: 24px;
        }

        .action-item__text {
          color: #333;
          font-size: 14px;
        }
      }
    }
  }

  .page-body {
    flex: 1;
    height: 0;
  }

  .page-footer {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 12px 12px 15px;
    background: #fff;

    .message-input {
      flex: 1;
      width: 0;

      ::v-deep .u-input {
        border-radius: 38px !important;
        border: none;
        background: #eee;
        padding-left: 12px !important;
        padding-right: 12px !important;
      }
    }

    .send-button {
      width: 64px;
      height: 32px;

      ::v-deep .u-button {
        background: #37AF71;
        border-radius: 8px;
        height: 34px;
        line-height: 34px;
        border: none;
      }
    }
  }

  .choose-file-image {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40upx 20upx 60upx;
    background: #f5f5f5;

    .choose-item {
      flex: 1;
      text-align: center;
    }
  }
}

.u-nav-slot {
  .username {
    font-weight: 500;
    font-size: 16px;
    color: #0D0D12;
    line-height: 24px;
    text-align: center;
  }

  .company-name {
    font-size: 12px;
    color: #333333;
    line-height: 25px;
    text-align: center;
  }
}

.modal-content-slot {
  line-height: 24px;

  .green-text {
    display: inline-block;
    color: #37AF71;
  }
}
</style>
